<?php

class country extends Model {
	private $_Name;
	private $_Flag;
	private $_Continent;
	
	private function _setDefaultValues($arrInitialValues = null){
		if (isset($arrInitialValues['name']) && !empty($arrInitialValues['name']))
			$this->setName($arrInitialValues['name']);
		else 
			$this->setName('');
			
		if (isset($arrInitialValues['flag']) && !empty($arrInitialValues['flag']))
			$this->setFlag($arrInitialValues['flag']);
		else 
			$this->setFlag('');
			
		if (isset($arrInitialValues['continent_name']) && !empty($arrInitialValues['continent_name']))
			$this->setContinent($arrInitialValues['continent_name']);
		else 
			$this->setContinent('');
	}
	
	private function fillMeIfHaveId(){
		$myId = $this->getId();
		
		if (isset($myId))
			$this->_getMe();
	}
	
	private function _getMe(){
		$me = $this->getOne();		
		
		if (isset($me[0]))
			$this->_setDefaultValues($me[0]);
	}
	
	public function getOne(){
		$query = '
			SELECT Cou.*, Con.name AS continent_name
			FROM ' . $this->getTable() . ' AS Cou
			INNER JOIN continents AS Con ON Cou.continent = Con.continent_id
			WHERE ' . $this->getColumnId() . ' = ' . $this->getId();

		$dbHelper = new DBHelper($query);
		return $dbHelper->getResult();
	}

	private function _getMeByName(){
		$query = '
			SELECT *
			FROM countries
			WHERE name = "' . $this->getDescription() . '"';

		$dbHelper = new DBHelper($query);
		return $dbHelper->getResult();		
	}
	
	public function getByName($Name){
		$this->setDescription($Name);
		$arrCountry = $this->_getMeByName();
		
		return new Country(
			array(
				"id" => $arrCountry[0]["country_id"], 
				"description" => $arrCountry[0]["name"], 
				"flag" => $arrCountry[0]["flag"]
			)
		);
	}
	
	public function __construct($arrInitialValues = null){
		$this->setTable('countries');
		$this->setColumnId('country_id');

		$this->_setDefaultValues($arrInitialValues);
		parent::__construct($arrInitialValues);
		
		$this->fillMeIfHaveId();
	}
	
	/**
	 * @return the $_Name
	 */
	public function getName() {
		return $this->_Name;
	}

	/**
	 * @return the $_Flag
	 */
	public function getFlag() {
		return $this->_Flag;
	}

	/**
	 * @return the $_Continent
	 */
	public function getContinent() {
		return $this->_Continent;
	}

	/**
	 * @param field_type $_Name
	 */
	public function setName($_Name) {
		$this->_Name = $_Name;
	}

	/**
	 * @param field_type $_Flag
	 */
	public function setFlag($_Flag) {
		$this->_Flag = $_Flag;
	}

	/**
	 * @param field_type $_Continent
	 */
	public function setContinent($_Continent) {
		$this->_Continent = $_Continent;
	}

}

?>